<template>
<div>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">{{dataForm}}
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px">
    <el-form-item label="面试公司" prop="interviewCompany">
      <el-input v-model="dataForm.interviewCompany" placeholder="面试公司"></el-input>
    </el-form-item>
    <el-form-item label="面试时间" prop="interviewTime">
      <el-date-picker
            style="width:100%;"
            v-model="dataForm.interviewTime"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
    </el-form-item>
    <el-form-item label="面试职位" prop="interviewPosition">
      <el-input v-model="dataForm.interviewPosition" placeholder="面试职位"></el-input>
    </el-form-item>
    <el-form-item label="面试地点" prop="interviewAddress">
      <div class="app-container">
        <el-autocomplete
          v-model="dataForm.interviewAddress"
          style="width:100%;"
          popper-class="autoAddressClass"
          :fetch-suggestions="querySearchAsync"
          :trigger-on-focus="false"
          placeholder="详细地址"
          clearable
          @select="handleSelect"
        >
          <template slot-scope="{ item }">
            <i class="el-icon-search fl mgr10" />
            <div style="overflow:hidden;">
              <div class="title">{{ item.title }}</div>
              <span class="address ellipsis">{{ item.address }}</span>
            </div>
          </template>
        </el-autocomplete>
        <div id="map-container" style="width:100%;height:220px;" />
  </div>
      <!-- <bmaps></bmaps>
      <el-input v-model="dataForm.interviewAddress" placeholder="面试地点" ></el-input>
       <el-button type="primary" @click="getAddress">选择地点</el-button> -->
    </el-form-item>
    <el-form-item label="来源" prop="interviewSource">
      <el-input v-model="dataForm.interviewSource" placeholder="来源"></el-input>
    </el-form-item>
    <el-form-item label="备注" prop="remarks">
      <el-input v-model="dataForm.remarks" placeholder="备注"></el-input>
    </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
    <!--地图-->

  </el-dialog>
</div>
</template>

<script> 
import loadBMap from '../../../utils/loadBMap.js'
 import AddOrUpdate from './interviewinvitationaddupdate'
  export default {
    components:{
      AddOrUpdate
    },
    data () {
      return {
        map: '', // 地图实例
        mk: '', // Marker实例
        locationPoint: null,
        id:null,
        readonly:true,
        visible: false,
        dataForm: {
          id: 0,
          interviewCompany: '',
          interviewTime: '',
          interviewPosition: '',
          interviewAddress: '',
          interviewSource: '',
          remarks: '',
          uid: '',
          number:0,
          address: '', // 详细地址
          addrPoint: { // 详细地址经纬度
            lng: 0,
            lat: 0
          }
        },
        dataRule: {
          interviewCompany: [
            { required: true, message: '面试公司不能为空', trigger: 'blur' }
          ],
          interviewPosition: [
            { required: true, message: '面试职位不能为空', trigger: 'blur' }
          ],
          interviewAddress: [
            { required: true, message: '面试地点不能为空', trigger: 'blur' }
          ],
          interviewSource: [
            { required: true, message: '来源不能为空', trigger: 'blur' }
          ],
          remarks: [
            { required: true, message: '备注不能为空', trigger: 'blur' }
          ],
        }
      }
    },
    methods: {
      init (id) {
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
          this.$http({
              url: this.$http.adornUrl(`/interview/interviewinvitation/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.interviewCompany = data.interviewInvitation.interviewCompany
                this.dataForm.interviewTime = data.interviewInvitation.interviewTime
                this.dataForm.interviewPosition = data.interviewInvitation.interviewPosition
                this.dataForm.interviewAddress = data.interviewInvitation.interviewAddress
                this.dataForm.interviewSource = data.interviewInvitation.interviewSource
                this.dataForm.remarks = data.interviewInvitation.remarks
                this.dataForm.uid = data.interviewInvitation.uid
                this.dataForm.number = data.interviewInvitation.number
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/interview/interviewinvitation/save`),
              method: 'post',
              data: this.$http.adornData({
                'interviewCompany': this.dataForm.interviewCompany,
                'interviewTime': this.dataForm.interviewTime,
                'interviewPosition': this.dataForm.interviewPosition,
                'interviewAddress': this.dataForm.interviewAddress,
                'interviewSource': this.dataForm.interviewSource,
                'remarks': this.dataForm.remarks,
                'number':this.dataForm.number+1,
                'uid': this.dataForm.uid
              })
            }).then(({data}) => {
              let id = data.id
                 this.$http({
                  url: this.$http.adornUrl(`/interview/interviewclass/save`),
                  method: 'post',
                  data: this.$http.adornData({
                    'studentId':1,
                    'tearcherId':1,
                    'status':0,
                    'resumeId':1,
                    'invitationId':id
                  })
                }).then(({data}) => {
                  this.$http({
                  url: this.$http.adornUrl(`/interview/interviewlog/save`),
                  method: 'post',
                  data: this.$http.adornData({
                    'studentId':1,
                    'identificationBit':1,
                    'invitationId':id,
                    'logTime': JSON.stringify([{status:0,date:new Date()}])
                  })
                }).then(({data}) => {
                })
                })
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      // 初始化地图
    initMap() {
      var that = this
      // 1、挂载地图
      this.map = new BMap.Map('map-container', { enableMapClick: false })
      var point = new BMap.Point(116.306529, 40.048434)
      this.map.centerAndZoom(point, 19)
      this.map.enableScrollWheelZoom(true)

      // 3、设置图像标注并绑定拖拽标注结束后事件
      this.mk = new BMap.Marker(point, { enableDragging: true })
      this.map.addOverlay(this.mk)
      this.mk.addEventListener('dragend', function(e) {
        that.getAddrByPoint(e.point)
      })

      // 4、添加（右上角）平移缩放控件
      this.map.addControl(new BMap.NavigationControl({ anchor: BMAP_ANCHOR_TOP_RIGHT, type: BMAP_NAVIGATION_CONTROL_SMALL }))

      // 5、添加（左下角）定位控件
      var geolocationControl = new BMap.GeolocationControl({ anchor: BMAP_ANCHOR_BOTTOM_LEFT })
      geolocationControl.addEventListener('locationSuccess', function(e) {
        that.getAddrByPoint(e.point)
      })
      geolocationControl.addEventListener('locationError', function(e) {
        alert(e.message)
      })
      this.map.addControl(geolocationControl)

      // 6、浏览器定位
      this.geolocation()

      // 7、绑定点击地图任意点事件
      this.map.addEventListener('click', function(e) {
        that.getAddrByPoint(e.point)
      })
    },
    // 获取两点间的距离
    getDistancs(pointA, pointB) {
      return this.map.getDistance(pointA, pointB).toFixed(2)
    },
    // 浏览器定位函数
    geolocation() {
      var that = this
      var geolocation = new BMap.Geolocation()
      geolocation.getCurrentPosition(function(res) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
          that.getAddrByPoint(res.point)
          that.locationPoint = res.point
        } else {
          alert('failed' + this.getStatus())
          that.locationPoint = new BMap.Point(116.306529, 40.048434)
        }
      }, { enableHighAccuracy: true })
    },
    // 2、逆地址解析函数
    getAddrByPoint(point) {
      var that = this
      var geco = new BMap.Geocoder()
      geco.getLocation(point, function(res) {
        console.log(res)
        that.mk.setPosition(point)
        that.map.panTo(point)
        that.dataForm.interviewAddress = res.address
        that.dataForm.addrPoint = point
      })
    },
    // 8-1、地址搜索
    querySearchAsync(str, cb) {
      var options = {
        onSearchComplete: function(res) {
          var s = []
          if (local.getStatus() == BMAP_STATUS_SUCCESS) {
            for (var i = 0; i < res.getCurrentNumPois(); i++) {
              s.push(res.getPoi(i))
            }
            cb(s)
          } else {
            cb(s)
          }
        }
      }
      var local = new BMap.LocalSearch(this.map, options)
      local.search(str)
    },
    // 8-2、选择地址
    handleSelect(item) {
      this.dataForm.interviewAddress = item.address + item.title
      this.dataForm.addrPoint = item.point
      this.map.clearOverlays()
      this.mk = new BMap.Marker(item.point)
      this.map.addOverlay(this.mk)
      this.map.panTo(item.point)
    },
    },
    async mounted() {
      await loadBMap() // 加载引入BMap
      this.initMap()
  },
  }
</script>
<style lang="scss" scoped>
.autoAddressClass{
  li {
    i.el-icon-search {margin-top:11px;}
    .mgr10 {margin-right: 10px;}
    .title {
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .address {
      line-height: 1;
      font-size: 12px;
      color: #b4b4b4;
      margin-bottom: 5px;
    }
  }
}
</style>
